package com.youu.youu.restapi.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.youu.youu.manager.bean.TUser;
import com.youu.youu.restapi.bean.ScwReturn;
import com.youu.youu.restapi.service.MessageService;
import com.youu.youu.restapi.service.UserService;

@RestController
public class UserController {

	@Autowired
	UserService userService;
	
	@Autowired
	MessageService messageService;

	
	
	
	//读取用户位置文件
	public String[] getUserLocationFile(HttpServletRequest request,String loginacct){
		StringBuilder sb = new StringBuilder();
		String fileaddress = "";
		String fileName = "";
		
		if("".equals(loginacct)){
			//用户为空，显示默认位置
			System.out.println("用户为空");
			
			fileaddress ="/admin/admin.txt";
			
			//1.获取某个文件夹在服务器上的真实路径
	        ServletContext context = request.getSession().getServletContext();
	        //2.使用context对象获取真实路径
	        String adPath = context.getRealPath("/personalFile");
	        System.out.println("默认文件位置:"+adPath);
	        
	       
	        fileName = adPath+fileaddress;
	        
		}else{
			
			
			fileaddress = "/"+loginacct+"/"+loginacct+"_LocationFile.txt";
			
			//1.获取某个文件夹在服务器上的真实路径
	        ServletContext context = request.getSession().getServletContext();
	        //2.使用context对象获取真实路径
	        String adPath = context.getRealPath("/personalFile");
			
			//通过用户名查询文件位置
			fileName = adPath+fileaddress;
		}
		
		
		
		
		
		
        byte[] buf=new byte[1024];  
        int len=0;  
        FileInputStream fInputStream = null;
		try {
			fInputStream = new FileInputStream(fileName);  
			while((len=fInputStream.read(buf))!=-1)  
			{  
				sb.append(new String(buf,0,len,"UTF-8"));
			}
			System.out.println("文件："+fileName+" 中的内容是:\n"+sb);
		}catch (IOException e1) {
			e1.printStackTrace();
		}  finally {
			//关闭流
			try {
				if(fInputStream!=null){
					fInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
        
		String[] split = sb.toString().split("-");
		
		return split;
        
		/*try {
            String encoding="UTF";
            File file = new File(fileaddress);
            System.out.println(file.getName());
            
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                }
                read.close();
	    }else{
	        System.out.println("找不到指定的文件");
	    }
	    } catch (Exception e) {
	        System.out.println("读取文件内容出错");
	        e.printStackTrace();
	    }*/
		
		
	}
	
	
	
	
	
	
	@RequestMapping("/login")
	public ScwReturn<TUser> login(@RequestParam("loginacct")String loginacct,@RequestParam("password")String password,@RequestParam("city")String city,@RequestParam("lng")String lng,@RequestParam("lat")String lat,HttpServletRequest request) {
		System.out.println("进入登录方法");
		
		if (StringUtils.isEmpty(password) && StringUtils.isEmpty(loginacct)) {
			// 输入不对
			return ScwReturn.fail("用户名和密码不能为空", null, null);
		}
		// 获取当前登录对象
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginacct,password);
		TUser tUser = new TUser();
		tUser.setLoginacct(loginacct);
		tUser.setPassword(password);
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			System.out.println("用户名或密码错误" + e);
			return ScwReturn.fail("用户名或密码错误", tUser, null);
		}
		
		System.out.println("成功");
		TUser user = userService.getManagerByLoginacc(loginacct);
		
		//Lux----->>>>>>>创建用户个人位置文件夹
		String userLocationFileDirPath = creatUserLocationFile(request,tUser);
		//Lux----->>>>>>>over
		
		
		
		//-------------------------------------------------------位置文件操作---------------------------------------------------
		//判断用户当前位置信息是否获取到，若没获取到则返回提示
		if("".equals(lng.trim())||"".equals(lat.trim())||"".equals(city.trim())){
			System.out.println("成功,但经纬度没获取到");
			TUser userNetError = userService.getManagerByLoginacc(loginacct);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("LocationMsg", "网路信号不通畅,未获取到位置信息,稍后重新登陆再试试~!");
			return ScwReturn.success("成功", userNetError, map);
		}
		
		StringBuilder sb = new StringBuilder();
		
		try {
			city = new String(city.getBytes(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		//用户当前位置拼串信息
		String nowLocationTest = lng+","+lat+","+city;
		String nowLocation = "-"+nowLocationTest+",200";
		System.out.println("查看用---->用户当前位置拼串结果: "+nowLocation);
		
		
		//对位置进行判断和写入操作
		//先读取用户位置文件
		String[] userLocationFile = getUserLocationFile(request, loginacct);
		
		
		
		System.out.println("查看用---->登陆用户读取对应位置文件，其长度是:"+userLocationFile.length);
		if(userLocationFile.length>0){
			for(int i=0;i<userLocationFile.length;i++){
				System.out.println("查看用---->用户位置文件第 "+i+" 位信息是:"+userLocationFile[i]);
			}
		}
		
		
		
		
		//用户第一次登陆，其位置文件按照"-"截取长度为1，内容是""
		if(userLocationFile.length==1 && "".equals(userLocationFile[0])){
			//用户第一次登陆直接写入当前位置
			sb.append(nowLocation);
		}else if(userLocationFile.length>1 && userLocationFile.length <=2){
			//位置信息只有一条时
			String substring = userLocationFile[1].substring(0, userLocationFile[1].lastIndexOf(","));
			System.out.println("仅有一条位置信息:"+substring);
			
			if(nowLocationTest.equals(substring)){
				//与当前位置一致
				sb.append(nowLocation);
			}else{
				//与当前位置不一致，修改value，追加至新串
				sb.append("-"+substring+",125");
				sb.append(nowLocation);
				
				// 与当前位置不一致，给用户发送消息提示
				messageService.addMsg(user.getId(), 19, new String[]{user.getLoginacct()});
			}
		}else{
			//用户不是第一次登陆
			//遍历所有位置信息
			for(int i = 1;i<userLocationFile.length;i++){
				
				String substring = userLocationFile[i].substring(0, userLocationFile[i].lastIndexOf(","));
				System.out.println("查看用---->截取出来的位置信息串是:"+substring);
				
				if(nowLocationTest.equals(substring)){
					//与当前位置一致，不追加至新串
				}else{
					//与当前位置不一致，修改value，追加至新串
					sb.append("-"+substring+",80");
				}
				
			}
			
			if(sb.toString().split("-").length>1&&sb.toString().split("-").length<=2){
				sb.replace(sb.lastIndexOf("80"), sb.lastIndexOf("80")+2, "125");
				sb.append(nowLocation);
			}else{
				//追加当前位置信息
				sb.append(nowLocation);
				
				//修改最后两个位置的value
				sb.replace(sb.lastIndexOf("-")-2, sb.lastIndexOf("-"), "125");
				
				sb.replace(sb.lastIndexOf("80"), sb.lastIndexOf("80")+2, "125");
			}
			
			if(!(sb.substring(sb.lastIndexOf("-"),sb.lastIndexOf(","))).split(",")[2].equals(city)){
				// 与上次登陆城市不一致，给用户发送消息提示
				messageService.addMsg(user.getId(), 19, new String[]{user.getLoginacct()});
			}
			
			System.out.println("测试------>>>>>：当前要重新写入的串是: "+sb);
		}
		
		
		String userLocationFileName = userLocationFileDirPath+"/"+loginacct+"_LocationFile.txt";
		File file = new File(userLocationFileName);
		
		OutputStreamWriter out = null;
		try {
			//先清空原文本，
			
			
			//重新写入新位置信息
			out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
			out.write(sb.toString().toCharArray());
		} catch (IOException e) {
			e.printStackTrace();
		}  finally {
			//关流
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		String tokend = UUID.randomUUID().toString().replace("-", "");
		System.out.println("数据库中的token"+tokend);
		user.setToken(tokend);
		boolean flag = userService.upDateByUser(user);
		return ScwReturn.success("成功", user, null);
	}

	/**
	 * 检测用户名是否存在 检查用户名密码是否正确 用户是否在线 在线 禁止登陆（后期做踢出在线用户） 未登录状态 允许登陆 修改登录状态 记录登录时间
	 */

	@RequestMapping("/regist")
	public ScwReturn<TUser> regist(TUser tUser, HttpServletRequest request,
			HttpSession session) {
		System.out.println("进入注册方法");
		if(tUser.getLoginacct()==null){
			
		}
		Map<String, Object> hashMap = new HashMap<>();

		boolean flag = false;
		try {

			// 创建用户个人位置文件夹
			creatUserLocationFile(request, tUser);

			flag = userService.register(tUser);
		} catch (Exception e) {
			System.out.println("注册失败");
			return ScwReturn.fail("注册失败", null, hashMap);
		}
		if (flag) {
			System.out.println("成功");
			
			// 获取用户id
			Integer uid = userService.getManagerByLoginacc(tUser.getLoginacct()).getId();
			// 给用户发送消息
			messageService.addMsg(uid, 31, new String[]{tUser.getLoginacct()});
			
			return ScwReturn.success("注册成功", tUser, null);
		} else {
			return ScwReturn.fail("注册失败", null, hashMap);
		}
	}

	
	
	
	
	public String creatUserLocationFile(HttpServletRequest request, TUser tUser) {
		// Lux-->用户注册成功，在restapi/webapp/personalFile下创建与此用户对应的文件夹，文件夹中创建位置文件

		String personalFilePath = "/personalFile";
		personalFilePath = request.getSession().getServletContext()
				.getRealPath(personalFilePath);
		System.out.println("personalFilePath--->" + personalFilePath);

		// 个人位置文件夹名(以用户名为文件名)
		String filePackageName = tUser.getLoginacct();
		String locationFileName = tUser.getLoginacct() + "_LocationFile.txt";
		// 创建个人文件夹
		File filePackage = new File(personalFilePath + "/" + filePackageName);
		System.out.println(filePackage.getPath());
		if (!filePackage.exists()) {
			filePackage.mkdir();

			// System.out.println("创建个人文件夹成功");

			// 创建个人位置文件(空)
			File UserLocationFile = new File(filePackage, locationFileName);

			if (!UserLocationFile.exists()) {// 如果不存在，就创建为文件
				try {
					UserLocationFile.createNewFile();

					// System.out.println("个人位置文件创建成功!");

					// 将个人文件夹位置放进数据库
					String userRelativeFilePath = UserLocationFile.getPath()
							.replace("\\", "/");
					System.out.println("个人为之文件存储路径是:" + userRelativeFilePath);
					tUser.setRelativeFilePath(userRelativeFilePath
							.substring(userRelativeFilePath
									.indexOf("/personalFile")));
					System.out.println("数据库中存的位置:"
							+ tUser.getRelativeFilePath());

				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("创建个人位置文件失败");
			}
		} else {
			System.out.println("创建个人文件夹失败");
		}
		// Lux--->创建文件夹over
		// -------------------------->>>>>这里需要注册成功后提示"注册成功，请登录!!!!"-----------不要直接去个人中心!----------------
		
		return filePackage.getPath();
	}

	/**
	 * 1.来到注册界面，通过失去焦点事件检测用户名邮箱是否合法唯一 2.保存用户信息 loginacct username password email
	 */
	// 检查邮箱唯一性
	@RequestMapping("/show/check")
	public boolean check(TUser tUser) {
		boolean b = userService.selectByTUser(tUser);
		return b;
		
	}

	@RequestMapping("/show/check1")
	public boolean check1(TUser tUser) {
		boolean b = userService.selectByTUser(tUser);
		return b;
	}
	
	@RequestMapping("/show/toVerifyToken")
	public ScwReturn<TUser> Verify(@RequestParam("token")String token){
	boolean flag = userService.selectByToken(token);
	if(flag){
		return ScwReturn.success("查询成功", null, null);
	}else{
		return ScwReturn.fail("用户失效，请重新登录！", null, null);
	}
	}
}
